package cn.cqautotest.cqviehelper.ui.activity;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PathUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import cn.cqautotest.cqviehelper.R;
import cn.cqautotest.cqviehelper.adapters.ItemRvFileListAdapter;
import cn.cqautotest.cqviehelper.base.BaseActivity;
import cn.cqautotest.cqviehelper.beans.FileInfo;
import cn.cqautotest.cqviehelper.config.AppConfig;
import cn.cqautotest.cqviehelper.ui.dialog.ToastDialog;
import cn.cqautotest.cqviehelper.utils.HandlerUtils;
import cn.cqautotest.cqviehelper.utils.LogUtils;
import cn.cqautotest.cqviehelper.utils.VerifyFileTypeUtils;

@SuppressLint("NonConstantResourceId")
public class FileManagerActivity extends BaseActivity implements OnPermission {

    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.tvPath)
    TextView tvPath;
    @BindView(R.id.rvFileList)
    RecyclerView rvFileList;
    private String currentPath = null;
    private boolean isShowHidden = false;
    private final List<FileInfo> fileInfoList = new ArrayList<>();
    private final List<FileInfo> tempData = new ArrayList<>(fileInfoList);

    private ItemRvFileListAdapter mFileListAdapter;
    private String mRootPath = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_file_manager;
    }

    @Override
    protected View getLayoutContainer() {
        return getContentView();
    }

    @Override
    protected void initEvent() {
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                // TODO: 2020/11/15 刷新当前所在路径的文件夹列表
                setupUI();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                new ToastDialog.Builder(FileManagerActivity.this).setMessage("已经到底啦").setDuration(600).create().show();
                refreshLayout.finishLoadmore();
            }
        });
        mFileListAdapter.setOnItemClickListener(fileInfo -> {
            if (fileInfo.isDirectory()) {
                currentPath = fileInfo.getPath();
                setupUI();
            } else {
                // TODO: 2020/11/16 判断文件是否存在
                LogUtils.d(this, String.format(" fileInfo is ======>%s", GsonUtils.toJson(fileInfo)));
                File file = fileInfo.getFile();
                Uri uri;
                try {
                    Intent intent = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = FileProvider.getUriForFile(this, AppConfig.getPackageName() + ".provider", file);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    } else {
                        uri = Uri.fromFile(file);
                    }
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, VerifyFileTypeUtils.getFileType(fileInfo.getAbsolutePath()));
                    startActivity(intent);
                } catch (ActivityNotFoundException | IllegalArgumentException | NullPointerException e) {
                    //e.printStackTrace();
                    new ToastDialog.Builder(this).setMessage("文件不存在").create().show();
                }
            }
        });
    }

    /**
     * 请求文件读写权限
     */
    @Override
    protected void initData() {
        XXPermissions.with(this).permission(Permission.Group.STORAGE).request(this);
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvFileList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mFileListAdapter = new ItemRvFileListAdapter();
        rvFileList.setLayoutManager(layoutManager);
        rvFileList.setAdapter(mFileListAdapter);
    }

    /**
     * 有文件读写权限的时候，获取根目录路径并更新文件列表
     *
     * @param granted
     * @param all
     */
    @Override
    public void hasPermission(List<String> granted, boolean all) {
        if (granted.containsAll(Arrays.asList(Permission.Group.STORAGE))) {
            mRootPath = currentPath = PathUtils.getExternalStoragePath();
            LogUtils.d(this, String.format("currentPath is =====> %s", currentPath));
            setupUI();
        }
    }

    /**
     * 异步刷新文件列表
     */
    private void setupUI() {
        HandlerUtils.getBackHandler().post(() -> {
            tvPath.setText(currentPath);
            List<File> files = FileUtils.listFilesInDir(currentPath);
            fileInfoList.clear();
            files = files.stream().peek(file -> {
                boolean isDirectory = file.isDirectory();
                //0代表隐藏的文件夹，1代表普通文件夹，2代表隐藏的文件，3代表普通文件
                int type = isDirectory ? file.isHidden() ? 0 : 1 : file.isHidden() ? 2 : 3;
                fileInfoList.add(new FileInfo(type, file.getName(), file).setHidden(file.isHidden()));
            }).collect(Collectors.toList());
            List<FileInfo> collect = fileInfoList.stream().sorted((o1, o2) -> o1.getFileName().compareTo(o2.getFileName())).sorted((o1, o2) -> o1.getFileType() - o2.getFileType()).collect(Collectors.toList());
            fileInfoList.clear();
            fileInfoList.addAll(collect);
            files.forEach(file -> {
                LogUtils.d(this, String.format("file path is %s", file.getAbsolutePath()));
            });
            tempData.clear();
            tempData.addAll(fileInfoList);
            // TODO: 2020/11/16 显示隐藏的文件及文件夹
            if (!isShowHidden) {
                // TODO: 2020/11/16 如果是显示状态，就不移除
                tempData.removeIf(FileInfo::isHidden);
            }
            HandlerUtils.getMainHandler().post(() -> {
                mFileListAdapter.setData(tempData);
                new ToastDialog.Builder(this).setMessage("文件列表更新完成").setDuration(600).create().show();
                refreshLayout.finishRefreshing();
            });
        });
    }

    /**
     * 没有文件读取权限的时候提示用户
     *
     * @param denied
     * @param quick
     */
    @Override
    public void noPermission(List<String> denied, boolean quick) {
        new ToastDialog.Builder(this).setMessage("没有存储权限").create().show();
        HandlerUtils.getMainHandler().postDelayed(() -> {
            if (!isDestroyed()) finish();
        }, 2000);
    }

    /**
     * 根据状态判断是退出本界面还是返回上一级目录
     */
    @Override
    public void onBackPressed() {
        File file = new File(currentPath);
        //判断当前路径是否为空，当前路径的文件对象是否为空，根目录路径是否为空，当前目录路径是否为根目录路径
        //如果为空，则退出本界面，不再执行返回上一级目录的操作
        if (TextUtils.isEmpty(currentPath) || file == null || mRootPath == null || mRootPath.equals(file.getPath())) {
            finish();
            return;
        }
        currentPath = file.getParent();
        LogUtils.d(this, String.format("onBackPressed：currentPath is =======>%s", currentPath));
        setupUI();
    }
}